#include "NWorld.h"
#include "NeroCore\NScope.h"
#include "NeroCore\NSector.h"
#include "NeroCore\NMemoryManager.h"

using namespace Game;
using namespace Core;

RTTI_DEFINITIONS(NWorld);

NWorldState* NWorld::WorldState = NULL;

NWorld::NWorld(void)
	:NAttributed()
{
	WorldState = MY_NEW(Memory::HID_Engine,"World State") NWorldState();
	WorldState->CurrentWorld = this;
}

NWorld::~NWorld(void)
{
	if(WorldState != NULL)
	{
		MY_DELETE(WorldState);
	}
	for(unsigned int i = 0; i < Size();i++)
	{
		NDatum & aDatum = (*this)[i];
		for(unsigned int j = 0 ; j < aDatum.GetNumValues(); j++)
		{
			NScope * aScope = aDatum.Get<NScope *>(j);
			if(aScope->Is("NSector"))
			{
				MY_DELETE(aScope);
			}
		}
	}
}

void NWorld::Initialize()
{
	for(unsigned int i = 0; i < Size();i++)
	{
		NDatum & aDatum = (*this)[i];
		for(unsigned int j = 0 ; j < aDatum.GetNumValues(); j++)
		{
			NScope * aScope = aDatum.Get<NScope *>(j);
			if(aScope->Is("NSector"))
			{
				//reinterpret_cast<NSector*>(aScope)->Initialize();
			}
		}
	}
}

void NWorld::Deinitialize()
{
	for(unsigned int i = 0; i < Size();i++)
	{
		NDatum & aDatum = (*this)[i];
		for(unsigned int j = 0 ; j < aDatum.GetNumValues(); j++)
		{
			NScope * aScope = aDatum.Get<NScope *>(j);
			if(aScope->Is("NSector"))
			{
				//reinterpret_cast<NSector*>(aScope)->Deinitialize();
			}
		}
	}
}

void NWorld::Update(float deltaTime)
{
	for(unsigned int i = 0; i < Size();i++)
	{
		NDatum & aDatum = (*this)[i];
		for(unsigned int j = 0 ; j < aDatum.GetNumValues(); j++)
		{
			NScope * aScope = aDatum.Get<NScope *>(j);
			if(aScope->Is("NSector"))
			{
				reinterpret_cast<NSector*>(aScope)->Update(deltaTime);
			}
		}
	}
}

void NWorld::Render(float deltaTime)
{
	for(unsigned int i = 0; i < Size();i++)
	{
		NDatum & aDatum = (*this)[i];
		for(unsigned int j = 0 ; j < aDatum.GetNumValues(); j++)
		{
			NScope * aScope = aDatum.Get<NScope *>(j);
			if(aScope->Is("NSector"))
			{
				reinterpret_cast<NSector*>(aScope)->Render(deltaTime);
			}
		}
	}
}

NScope& NWorld::GetSectors()
{
	return *this;
}

Core::NScope& NWorld::AppendSector(std::string sectorName, Core::NSector* )
{
	NSector* newSector = MY_NEW(Memory::HID_Game,"New Sector") NSector();
	/*newSector->SetWorld(this);
	Adopt(newSector,sectorName.c_str(),Size());

	mSectorList.push_back(newSector);

	WorldState->CurrentSector = mSectorList[mSectorList.size()-1];*/
	return *newSector;
}

NWorldState& NWorld::GetWorldState()
{
	return *WorldState;
}